# -*- coding: utf-8 -*-

"""StaffLog - Terminal
@version: 0.1
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez <jajimc@gmail.com>, Miguel Centeno <miguelcent@gmail.com>"""

import gtk
import threading
import time
from opencv.cv import *
from opencv.highgui import *
import diallogin
import dialsuccess
import dialerror
import images
import predesys

class WinMain:
    def __init__(self):
        self.gladeFile = "winsetup.glade"
        self.builder = gtk.Builder()
        self.builder.add_from_file(self.gladeFile)
        self.winMain = self.builder.get_object("winMain")
        self.imgDevice = self.builder.get_object("imgDevice")
        self.labDescription = self.builder.get_object("labDescription")
        self.spinState = self.builder.get_object("spinState")
        self.labState = self.builder.get_object("labState")
        self.butRegister = self.builder.get_object("butRegister")
        self.butCapture = self.builder.get_object("butCapture")
        self.imgFaceDetected = self.builder.get_object("imgFaceDetected")
        self.imgLeftEyeDetected = self.builder.get_object("imgLeftEyeDetected")
        self.imgRightEyeDetected = self.builder.get_object("imgRightEyeDetected")
        self.imgNoseDetected = self.builder.get_object("imgNoseDetected")
        self.imgMouthDetected = self.builder.get_object("imgMouthDetected")
        self.labDetectionSuccess = self.builder.get_object("labDetectionSuccess")
        
        self.builder.connect_signals(self)
        self.winMain.show_all()
        
        self.doDetection = True
        self.captureThread = VideoCaptureThread(self)
        self.captureThread.start()
        
    def on_winmain_delete(self, widget, event):
        return False
        
    def on_winmain_destroy(self, widget):
        self.captureThread.close()
        gtk.main_quit()
        
    def on_butcapture_clicked(self, widget):
        self.doDetection = True
        self.labDescription.set_visible(True)
        self.imgFaceDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
        self.imgLeftEyeDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
        self.imgRightEyeDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
        self.imgNoseDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
        self.imgMouthDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
        self.labDetectionSuccess.set_visible(False)
        self.spinState.set_visible(True)
        self.labState.set_text("Capturando...")
        self.butCapture.set_sensitive(False)
        self.butRegister.set_sensitive(False)
        
    def on_butregister_click(self, widget):
        d = diallogin.DialLogin()
        result = d.run()
        
        if result == gtk.RESPONSE_OK:
            try:
                success = predesys.set_up(d.host, d.port, d.userId, d.userPassword, self.eyesDistance, self.horLeftEyeNoseDistance, self.verLeftEyeNoseDistance, self.noseMouthDistance)
                if success:
                    d = dialsuccess.DialSuccess("Setup realizado con éxito")
                else:
                    d = dialerror.DialError("Ha ocurrido un error al llamar al servicio de Setup")
                d.run()
            except:
                d = dialerror.DialError("Ha ocurrido un error al llamar al servicio de Setup")
                d.run()
        
class VideoCaptureThread(threading.Thread):
    def __init__(self, mainWindow):
        self.mainWindow = mainWindow
        self.capture = self.capture = cvCreateCameraCapture(0)
        self.capturing = True
        threading.Thread.__init__(self)
    
    def run(self):
        while self.capturing:
            try:
                self.video_capture()
            except Exception as exc:
                print "Error: \"" + str(exc) + "\""    
            time.sleep(0.03)
            
    def close(self):
        self.capturing = False
            
    def video_capture(self):
        frame = cvQueryFrame(self.capture)
        
        if frame != None and self.mainWindow.doDetection:
            currentFaceImage, faceRegion, leftEyeRegion, rightEyeRegion, noseRegion, mouthRegion = images.detect_face(frame)
            faceDetected = (faceRegion != None)
            leftEyeDetected = (leftEyeRegion != None)
            rightEyeDetected = (rightEyeRegion != None)
            noseDetected = (noseRegion != None)
            mouthDetected = (mouthRegion != None)
            validFace = (faceDetected and leftEyeDetected and rightEyeDetected and noseDetected and mouthDetected)
            
            if validFace:
                self.mainWindow.doDetection = False
                self.mainWindow.labDescription.set_visible(False)
                self.mainWindow.labDetectionSuccess.set_visible(True)
                self.mainWindow.spinState.set_visible(False)
                self.mainWindow.labState.set_text("Imagen congelada")
                self.mainWindow.butCapture.set_sensitive(True)
                self.mainWindow.butRegister.set_sensitive(True)
                
                self.mainWindow.eyesDistance, self.mainWindow.horLeftEyeNoseDistance, self.mainWindow.verLeftEyeNoseDistance, self.mainWindow.noseMouthDistance = images.get_distances(leftEyeRegion, rightEyeRegion, noseRegion, mouthRegion)

            if faceDetected:
                self.mainWindow.imgFaceDetected.set_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_BUTTON)
            else:
                self.mainWindow.imgFaceDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
                
            if leftEyeDetected:
                self.mainWindow.imgLeftEyeDetected.set_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_BUTTON)
            else:
                self.mainWindow.imgLeftEyeDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
                
            if rightEyeDetected:
                self.mainWindow.imgRightEyeDetected.set_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_BUTTON)
            else:
                self.mainWindow.imgRightEyeDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
                
            if noseDetected:
                self.mainWindow.imgNoseDetected.set_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_BUTTON)
            else:
                self.mainWindow.imgNoseDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
                
            if mouthDetected:
                self.mainWindow.imgMouthDetected.set_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_BUTTON)
            else:
                self.mainWindow.imgMouthDetected.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
            
            cvFlip(frame, None, 1)
            self.mainWindow.imgDevice.set_from_pixbuf(images.ipl_to_pixbuf(frame))
